package com.medvalley.tcm.controller.admin.controller;

import com.google.common.collect.Maps;
import com.medvalley.tcm.base.Constants;
import com.medvalley.tcm.base.Result;
import com.medvalley.tcm.cache.RedisCache;
import com.medvalley.tcm.controller.BaseController;
import com.medvalley.tcm.controller.admin.service.ManagerService;
import com.medvalley.tcm.controller.admin.vo.inputvo.ManagerUserInputVo;
import com.medvalley.tcm.controller.admin.vo.outputvo.ManagerUserOutputVo;
import com.medvalley.tcm.controller.admin.vo.outputvo.PageDataOutputVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author linsong
 * @date 2019/6/20 14:29
 **/

@RestController
@RequestMapping("/manager")
@Api("管理员接口")
public class ManagerController extends BaseController {

    @Autowired
    private ManagerService managerService;

    @Autowired
    private RedisCache redisCache;

    @ApiOperation("登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestParam String name, @RequestParam String password) {
        ManagerUserOutputVo managerUserOutputVo = managerService.login(name, password);
        Map<String, Object> retMap = Maps.newHashMap();
        String token = this.generateToken(name);
        retMap.put("token", token);
        retMap.put("userInfo", managerUserOutputVo);
        return success(retMap);
    }

    @ApiOperation("删除用户")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Result delete(@RequestParam int id) {
        managerService.delete(id);
        return success();
    }

    @ApiOperation("创建管理员")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Result create(@ModelAttribute ManagerUserInputVo managerUserInputVo) {
        managerService.createManager(managerUserInputVo);
        return success();
    }

    @ApiOperation("检索全新大于0的管理员")
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result search(@RequestParam int pageNo, @RequestParam int pageSize) {
        PageDataOutputVo<ManagerUserOutputVo> pageDataOutputVo = managerService.searchManagerUser(pageNo, pageSize);
        return success(pageDataOutputVo);
    }

    private String generateToken(String phone) {
        String token = DigestUtils.md5DigestAsHex(phone.getBytes());
        redisCache.setValue(Constants.SESSION_PREFIX + token, phone);
        return token;
    }
}
